package com.sctvcloud.bazhong.ui.activities;

import android.Manifest;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.sunflower.FlowerCollector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.sctvcloud.bazhong.R;
import com.sctvcloud.bazhong.base.BaseActivity;
import com.sctvcloud.bazhong.ui.utils.JsonParser;
import com.sctvcloud.bazhong.ui.utils.PermissionUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.Event;

import java.util.HashMap;
import java.util.LinkedHashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 语音搜集页
 */
public class SpeakActivity extends BaseActivity implements View.OnTouchListener {
    @BindView(R.id.speak_knob)
    protected CustomFontTextView speak_knob;
    @BindView(R.id.speak_condition)
    protected CustomFontTextView speak_condition;
    @BindView(R.id.speak_change_big)
    protected ImageView speak_change;
    // 语音听写对象
    private SpeechRecognizer mIat;
    // 用HashMap存储听写结果
    private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;
    private int ret = 0; // 函数调用返回
    public static final String SEARCH_KEY = "search_key";
    private String search;
    //存储很多张话筒图片的数组
    private Drawable[] micImages;
    private static final long SPACE = 200;
    private int voice;
    private boolean isTouching;
    private final Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            int what = msg.what;
            //说话声音越大,发送过来what值越大
            if (what > 2) {
                what = 2;
            }
            speak_change.setImageDrawable(micImages[what]);
        }
    };
    private PermissionUtils mPermissionUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checkRecordPermission();
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_speak);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        FlowerCollector.onResume(SpeakActivity.this);
        FlowerCollector.onPageStart("");
        super.onResume();
    }

    @Override
    protected void onPause() {
        FlowerCollector.onPageEnd("");
        FlowerCollector.onPause(SpeakActivity.this);
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacks(mUpdateMicStatusTimer);
        if (null != mIat) {
            // 退出时释放连接
            mIat.cancel();
            mIat.destroy();
        }
    }

    @OnClick({R.id.speak_cancel})
    public void cancelClick(View view) {
        switch (view.getId()) {
            case R.id.speak_cancel:
                if (!isTouching) {
                    onBackPressed();
                }
                break;
        }
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                isTouching = true;
                startRecord();
                return true;

            case MotionEvent.ACTION_MOVE:
                return true;
            case MotionEvent.ACTION_UP:
                if (mIat.isListening()) {
                    mIat.stopListening();
                    if (!TextUtils.isEmpty(search)) {
                        setResultes(1);
                    } else {
                        toast("没听清,请重试");
                    }

                }
                isTouching = false;

                return true;
            case MotionEvent.ACTION_CANCEL:
                isTouching = false;
            case MotionEvent.ACTION_OUTSIDE:
                isTouching = false;
            default:
                return false;
        }
    }

    private void initView() {
        speak_knob.setOnTouchListener(this);
        // 初始化识别无UI识别对象
        // 使用SpeechRecognizer对象，可根据回调消息自定义界面；
        mIat = SpeechRecognizer.createRecognizer(SpeakActivity.this, null);
        // 动画资源文件,用于录制语音时
        micImages = new Drawable[]{
                getResources().getDrawable(R.mipmap.icon_search_voiceing),
                getResources().getDrawable(R.mipmap.icon_speak_small_circle),
                getResources().getDrawable(R.mipmap.icon_speak_big_circle),};
    }

    private void checkRecordPermission() {
        mPermissionUtils = new PermissionUtils(this);
        mPermissionUtils.addPermission(Manifest.permission.RECORD_AUDIO);

        mPermissionUtils.setPermissionListener(new PermissionUtils.PermissionListener() {
            @Override
            public void onUserRefusesPermissions() {
                toast("用户拒绝了权限，无法使用录音功能, 如需重新授予权限，请进入手机的“设置-应用程序-SiChuanFocus2Android”中打开权限");
            }
        });

        if (mPermissionUtils.checkAndRequestPermissions()) {
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            toast("用户拒绝了权限，无法使用录音功能, 如需重新授予权限，请进入手机的“设置-应用程序-SiChuanFocus2Android”中打开权限");
        }
    }

    private void startRecord() {
        mIatResults.clear();
        // 设置参数
        setParam();
        ret = mIat.startListening(mRecognizerListener);
        if (ret != ErrorCode.SUCCESS) {
            toast("识别失败,错误码：" + ret);
        }
    }

    /**
     * 参数设置
     *
     * @param
     * @return
     */
    public void setParam() {
        // 清空参数
        mIat.setParameter(SpeechConstant.PARAMS, null);

        // 设置听写引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");

        // 设置语言
        mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        // 设置语言区域
        mIat.setParameter(SpeechConstant.ACCENT, "mandarin");

        mIat.setParameter(SpeechConstant.VAD_BOS, "4000");

        mIat.setParameter(SpeechConstant.VAD_EOS, "1500");
    }

    private void printResult(RecognizerResult results) {
        String text = JsonParser.parseIatResult(results.getResultString());
        String sn = null;
        // 读取json结果中的sn字段
        try {
            JSONObject resultJson = new JSONObject(results.getResultString());
            sn = resultJson.optString("sn");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mIatResults.put(sn, text);

        StringBuffer resultBuffer = new StringBuffer();
        for (String key : mIatResults.keySet()) {
            resultBuffer.append(mIatResults.get(key));
        }
        search = resultBuffer.toString();
    }

    /**
     * 语音听写监听器
     */
    private RecognizerListener mRecognizerListener = new RecognizerListener() {

        @Override
        public void onBeginOfSpeech() {
        }

        @Override
        public void onError(SpeechError error) {
            //  toast(error + "");
        }

        @Override
        public void onEndOfSpeech() {
        }

        @Override
        public void onResult(RecognizerResult results, boolean isLast) {
            printResult(results);
        }

        @Override
        public void onVolumeChanged(int volume, byte[] data) {
            voice = volume;
            updateVoiceStatus(voice);
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {

        }
    };


    private void updateVoiceStatus(int voice) {
        mHandler.postDelayed(mUpdateMicStatusTimer, SPACE);
        JLog.e("voice=" + voice);
        mHandler.sendEmptyMessage(voice / 8);
    }

    private Runnable mUpdateMicStatusTimer = new Runnable() {
        public void run() {
            updateVoiceStatus(voice);
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PermissionUtils.PERMISSIONS_REQUEST_CODE) {
            String msg = "本页面的语音功能需要用到录音权限";
            if (mPermissionUtils.recheckPermissions(grantResults, msg)) {
                startRecord();
            }
        }
    }

    @Override
    public void onBackPressed() {
        setResultes(-1);
        super.onBackPressed();
    }

    private void setResultes(int pos) {
        Intent intent = getIntent();
        if (pos > 0) {
            if (!TextUtils.isEmpty(search)) {
                intent.putExtra(SEARCH_KEY, search);
            }
        }
        setResult(SearchActivity.RESULT_CODE, intent);
        finish();
    }
}
